package com.example.practice;

import java.util.concurrent.atomic.AtomicStampedReference;

/**
 * Created by IntelliJ IDEA2021.3
 *
 * @Author: Tenghw
 * @Date: 2022/10/08  13:41
 * @Description:
 */
@SuppressWarnings("All")
public class ABASolution {
    //创建变量，第一个是initialRef为初始值，第二个是initialStamp为初始化时间戳
    static AtomicStampedReference<Integer> atomicStampedReference = new AtomicStampedReference<>(100, 1);

    public static void main(String[] args) {
        //atmoinReferenceMethod();
        new Thread(() -> {
            //获得时间戳，此时为1
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t第1次版本号" + stamp);
            try {
                //此处休眠的目的是为了让t2获得初始版本号
                Thread.sleep(1000);
                //第一次修改，值改为101，版本号加1
                atomicStampedReference.compareAndSet(100, 101, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
                System.out.println(Thread.currentThread().getName() + "\t第2次版本号" + atomicStampedReference.getStamp() + "----此时值为" + atomicStampedReference.getReference());
                //第二次修改，值改为100，版本号加1
                atomicStampedReference.compareAndSet(101, 100, atomicStampedReference.getStamp(), atomicStampedReference.getStamp() + 1);
                System.out.println(Thread.currentThread().getName() + "\t第3次版本号" + atomicStampedReference.getStamp() + "----此时值为" + atomicStampedReference.getReference());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t1").start();

        new Thread(() -> {
            //获得时间戳，此时为1
            int stamp = atomicStampedReference.getStamp();
            System.out.println(Thread.currentThread().getName() + "\t第1次版本号" + stamp);
            try {
                //休眠2秒，此时线程t1已经将值改变但是又变回来，为ABA问题
                Thread.sleep(2000);
                //获得时间戳，此时为3
                int stamp1 = atomicStampedReference.getStamp();
                System.out.println(Thread.currentThread().getName() + "\t此时时间戳=" + stamp1);
                //首先尝试是否可以根据值和时间戳进行更改
                boolean result = atomicStampedReference.compareAndSet(100, 102, stamp, stamp + 1);
                System.out.println(Thread.currentThread().getName() + "\t修改是否成功？=" + result + "\t当前最新实际版本号" + atomicStampedReference.getStamp() + "----此时值为" + atomicStampedReference.getReference());
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }, "t2").start();
    }
}
